package util

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

type HttpUtil struct {
	client *resty.Client
}

func NewHttpUtil() *HttpUtil {
	currentClient := resty.New()
	currentClient.SetTimeout(time.Duration(60 * time.Second))
	return &HttpUtil{
		client: currentClient,
	}
}

func (h *HttpUtil) GetResty(url string) *resty.Response {
	res, err := h.client.R().Get(url)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return res
}

func (h *HttpUtil) GetHeadResty(url string, headKey string, headValue string) *resty.Response {
	r := h.client.R()
	r.SetHeader(headKey, headValue)
	res, err := r.Get(url)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return res
}

func (h *HttpUtil) PostResty(url string, json map[string]interface{}) *resty.Response {
	r := h.client.R()
	if json != nil {
		r.SetBody(json)
	}
	res, err := r.Post(url)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return res
}

func (h *HttpUtil) PostFormResty(url string, formData map[string]string) *resty.Response {
	r := h.client.R()
	if formData != nil {
		r.SetFormData(formData)
	}
	res, err := r.Post(url)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return res
}

func (h *HttpUtil) PostNoParamResty(url string) *resty.Response {
	r := h.client.R()
	res, err := r.Post(url)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return res
}

func (h *HttpUtil) Get(url string) string {
	response, err := http.Get(url)
	if err != nil {
		return ""
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return ""
	}
	return string(body)
}

func (h *HttpUtil) GetRes(url string) *http.Response {
	response, err := http.Get(url)
	if err != nil {
		return nil
	}
	return response
}

func (h *HttpUtil) GetHead(url string, headKey string, headValue string) []byte {
	client := &http.Client{
		Timeout: 10 * time.Second,
	}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("创建http请求失败->", err)
		return nil
	}
	request.Header.Set(headKey, headValue)
	response, err := client.Do(request)
	if err != nil {
		return nil
	}
	defer response.Body.Close()
	all, err := io.ReadAll(response.Body)
	if err != nil {
		return nil
	}
	return all
}

func (h *HttpUtil) Post(url string) *http.Response {
	response, err := http.PostForm(url, make(map[string][]string))
	if err != nil {
		return nil
	}
	return response
}
